package com.estore;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ConsoleShop {
    private static ProductService productService = new ProductService();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        showMainMenu();
    }

    private static void showMainMenu() {
        boolean running = true;
        while (running) {
            System.out.println("\n===== 电子书店 =====");
            System.out.println("1. 浏览所有商品");
            System.out.println("2. 排序浏览商品（按ID）");
            System.out.println("3. 退出");
            System.out.print("请选择操作：");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    browseAllProducts();
                    break;
                case 2:
                    browseSortedProducts();
                    break;
                case 3:
                    running = false;
                    System.out.println("感谢使用，再见！");
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
        scanner.close();
    }

    /**
     * 浏览所有商品（原始顺序）
     */
    private static void browseAllProducts() {
        System.out.println("\n===== 所有商品 =====");
        Map<String, Product> products = productService.getAllProducts();
        for (Product product : products.values()) {
            System.out.println(product);
        }
    }

    /**
     * 排序浏览商品（按ID自然排序）
     */
    private static void browseSortedProducts() {
        System.out.println("\n===== 排序后商品（按ID） =====");
        Map<String, Product> products = productService.getAllProducts();
        List<Product> productList = new ArrayList<>(products.values());
        Collections.sort(productList); // 利用Product实现的Comparable接口排序

        for (Product product : productList) {
            System.out.println(product);
        }
    }
}